<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\common\logic;

use think\Db;
use think\facade\Log;

class OrderLogic extends BaseLogic
{
    public function __construct($tableName = 'Order'){
        parent::__construct($tableName);
    }

    /**
     * 统一处理订单条件和列
     * @param $where
     * @param string $order
     * @param int $isDel
     * @return \think\db\Query
     */
    private function _handleOrderPagerWhere($where, $order = '',$isDel = 0){
        $tableDb = Db::name('Order');

        $field[] = 'o.*';
        // __MEMBER__
        $field[] = 'm.nickname AS m_nickname';
        $field[] = 'm.realname AS m_realname';
        $field[] = 'm.mobile AS m_mobile';
        $field[] = 'm.avatar AS m_avatar';
        // __ORDER_PRICE__
        $field[] = 'op.dispatch_price_change';
        $field[] = 'op.total_price_change';
        // __ORDER_ADDRESS__
        $field[] = 'oa.address_json';
        // __ORDER_EXPRESS__
        $field[] = 'oe.express_com AS oe_express_com';
        $field[] = 'oe.express AS oe_express';
        $field[] = 'oe.express_sn AS oe_express_sn';
        $field[] = 'oe.update_time AS oe_update_time';

        //带软删除 $isDel = 1 查询出已经删除了的数据
        if(!empty($isDel)){
            $where[] = ['o.delete_time','>',0];
        }
        else{
            $where[] = ['o.delete_time','<',1];
        }
        $tableDb->alias('o')->field(join(',',$field))
            ->join('__MEMBER__ m','m.id = o.member_id','LEFT')
            ->join('__ORDER_PRICE__ op','op.order_id = o.id','LEFT')
            ->join('__ORDER_ADDRESS__ oa','oa.order_id = o.id','LEFT')
            ->join('__ORDER_EXPRESS__ oe','oe.order_id = o.id','LEFT')
            ->where($where)->order($order);

        return $tableDb;
    }

    public function _getOrderPager($where, $offset = 0, $limit = 0,$order = '',$isDel = 0){
        $tableDb = $this->_handleOrderPagerWhere($where, $order, $isDel);

        if($limit > 0){
            $tableDb->limit($offset, $limit);
        }

        $dataList = $tableDb->select();


        foreach ($dataList as $key => $item) {
            // 解析收货地址
            if(!empty($item['address_json'])){
                $tmp = json_decode($item['address_json'], true);
                if (!empty($tmp)) {
                    $dataList[$key]['address'] = $tmp;
                }
            }
            // 增加子订单
            $dataList[$key]['subs'] = $this->_getOrderSubByOrderId($item['id']);

            // status 大于 1 不进行支付日志查询
            // 支付日志
            if($item['status'] > 1){
                $dataList[$key]['pay_log'] = $this->_getOrderPayLogListByOrderId($item['id']);
            }
            else{
                $dataList[$key]['pay_log'] = [];
            }
        }

        return $dataList;
    }

    public function _getOrderPagerCountByWhere($where = [],$isDel = 0){
        $tableDb = $this->_handleOrderPagerWhere($where, '', $isDel);
        return $tableDb->count();
    }

    /**
     * 保存订单
     * @param $memberId
     * @param array $addressModel
     * @param array $goodsList  ['goods_name'=>'商品名称' , 'options' => ['id' => 1 , 'title' => '规格标题']  ]
     * @param array $totalMap 购买数量对应  [ '商品ID' _ '规格ID' => '数量' ]
     * @param array $cartIds
     * @param $remark
     * @return array
     */
    public function saveOrder($memberId,array $addressModel,array $goodsList,array $totalMap,array $cartIds,$remark = ''){
        if (empty($memberId)) {
            return $this->retError('会员信息无效，请重新登陆');
        }
        if (empty($addressModel)) {
            return $this->retError('地址信息无效，请重新登陆');
        }
        if (empty($goodsList)) {
            return $this->retError('商品信息无效，请重新登陆');
        }

        // 启动事务
        Db::startTrans();
        try {
            $orderNo = build_order_no();
            // 计算总价
            $totalPrice = $this->_calcTotalPrice($goodsList,$totalMap);
            $orderData = [
                'order_no' => $orderNo,
                'member_id' => $memberId,
                'address_id' => $addressModel['id'],
                'total_price' => $totalPrice,
                'original_total_price' => $totalPrice,
                'remark' => $remark,
                'status' => 1,
                'create_time' => time(),

                'book_realname' => $addressModel['realname'],
                'book_mobile' => $addressModel['mobile'],
            ];

            $orderId = Db::name('Order')->insertGetId($orderData);

            if($orderId < 1){
                exception('插入 Order 失败 '.json_encode($orderData,256));
            }

            // 剔除掉 address mode 的 id
            unset($addressModel['id']);
            $orderAddressData = [
                'order_id' => $orderId,
                'address_json' => json_encode($addressModel,256),
            ];
            // 保存地址
            $orderAddressId = Db::name('OrderAddress')->insertGetId($orderAddressData);
            if($orderAddressId < 1){
                exception('插入 OrderAddress 失败 '.json_encode($orderAddressData,256));
            }
            // 插入子订单
            foreach ($goodsList as $item) {
                $orderSubData = [
                    'order_id' => $orderId,
                    'goods_id' => $item['id'],
                    'goods_name' => $item['goods_name'],
                    'sub_title' => $item['sub_title'],
                    'goods_thumbs' => $item['thumbs'],
                    'goods_cates' => $item['cates'],

                    'total' => $totalMap[   $item['id'] . '_' . $item['options']['id']    ],
                ];
                // 2018.09.26  规格 信息 新版本必须有规格
                if(empty($item['options'])){
                    exception('找不到规格 $item ' . json_encode($item,256));
                }

                $orderSubData['product_price'] = $item['options']['product_price'];
                $orderSubData['market_price'] = $item['options']['market_price'];
                $orderSubData['cost_price'] = $item['options']['cost_price'];

                $orderSubData['goods_option_id'] = $item['options']['id'];
                $orderSubData['goods_option_title'] = $item['options']['title'];
                $orderSubData['goods_option_thumb'] = $item['options']['thumb'];

                $orderSubData['goods_option_specs'] = $item['options']['specs'];


                $orderSubId = Db::name('OrderSub')->insertGetId($orderSubData);
                if($orderSubId < 1){
                    exception('插入 OrderSub 失败 ' . json_encode($orderSubData,256));
                }

                // 插入子订单快照
                $orderSubSnapshotData = [
                    'order_sub_id' => $orderSubId,
                    'goods_json' => json_encode($item,256),
                ];
                $orderSubSnapshotId = Db::name('OrderSubSnapshot')->insertGetId($orderSubSnapshotData);
                if($orderSubSnapshotId < 1){
                    exception('插入 OrderSubSnapshot 失败 ' . json_encode($orderSubSnapshotData,256));
                }
            }

            // 删除购物车内容
            if (!empty($cartIds)) {
                $memberLogic = new MemberLogic();
                $jieguo = $memberLogic->_delCartByIds($memberId, $cartIds);
                if (false === $jieguo) {
                    exception('删除购物车 失败 $cartIds ' . json_encode($cartIds,256));
                }
            }

            // 提交事务
            Db::commit();

            return $this->retSuccess('提交订单成功',[
                'order_id'=>$orderId,
            ]);
        } catch (\Exception $e) {
            // 统一处理错误日志
            Log::error('OrderLogic => saveOrder ' . $e->getMessage());
            // 回滚事务
            Db::rollback();

            return $this->retError('提交订单错误，请联系管理员');
        }
    }

    /**
     * 目前只允许 saveOrder 里面调用
     * @param array $goodsList
     * @param array $totalMap
     * @return float|int
     * @throws \Exception
     */
    private function _calcTotalPrice(array $goodsList,array $totalMap){
        if(count($totalMap) != count($goodsList)){
            exception(' OrderLogic => _calcTotalPrice 提交商品数量和数据库商品不一致 $totalMap ' . json_encode($totalMap,256) . ' $goodsList ' . json_encode($goodsList,256));
        }

        $price = 0;
        foreach ($goodsList as $item) {
            // 2018.09.26 新版 使用 规格 options 进行计算
            if(!empty($item['options'])){
                $price += $item['options']['market_price'] * $totalMap[ $item['id'] . '_' . $item['options']['id'] ];
            }
        }
        return $price;
    }

    public function _getOrderModelByWhere($where){
        $dataList = $this->_getOrderPager($where,0,1);
        if(count($dataList) > 0){
            return $dataList[0];
        }
        else{
            return [];
        }
    }

    public function _getOrderModelById($orderId,$memberId = 0){
        $where[] = ['o.id','=',$orderId];
        if(!empty($memberId)){
            $where[] = ['o.member_id','=',$memberId];
        }
        return $this->_getOrderModelByWhere($where);
    }

    public function _getOrderSubByOrderId($orderId){
        return Db::name('OrderSub')->where('order_id', $orderId)->select();
    }

    /**
     * 设置 订单 改价
     * @param int $orderId
     * @param int $adminId  操作员
     * @param $postData
     */
    public function changeOrderPrice($orderId,$adminId,$postData){
        if (empty($orderId)) {
            return $this->retError('订单序号 无效，请重新登陆');
        }
        if (empty($adminId)) {
            return $this->retError('管理员信息 无效，请重新登陆');
        }
        $model = Db::name('OrderPrice')->where('order_id',$orderId)->find();

        // 启动事务
        Db::startTrans();
        try {
            $newData = [
                'dispatch_price_change' => yuanToFen($postData['dispatch_price_change']),
                'total_price_change' => yuanToFen($postData['total_price_change']),
            ];
            if (empty($model)) {
                $insertData = [
                    'order_id' => $orderId,
                    'dispatch_price_change' => $newData['dispatch_price_change'],
                    'total_price_change' => $newData['total_price_change'],
                ];
                $jieguo = Db::name('OrderPrice')->insertGetId($insertData);
                if ($jieguo < 1) {
                    exception('插入 OrderPrice 失败 '.json_encode($insertData,256));
                }
                $oldData = [
                    'dispatch_price_change' => 0,
                    'total_price_change' => 0,
                ];
            }
            else{
                $updateData = [
                    'dispatch_price_change' => $newData['dispatch_price_change'],
                    'total_price_change' => $newData['total_price_change'],
                ];
                $jieguo = Db::name('OrderPrice')->where('order_id',$orderId)->setField($updateData);
                if (false === $jieguo) {
                    exception('更新 OrderPrice 失败 '.json_encode($updateData,256));
                }
                $oldData = [
                    'dispatch_price_change' => $model['dispatch_price_change'],
                    'total_price_change' => $model['total_price_change'],
                ];
            }
            // 写日志
            $logData = [
                'order_id' => $orderId,
                'admin_id' => $adminId,
                'old_data' => json_encode($oldData,256),
                'new_data' => json_encode($newData,256),
                'create_time' => time(),
            ];
            $jieguo = Db::name('OrderPriceLog')->insertGetId($logData);
            if ($jieguo < 1) {
                exception('插入 OrderPriceLog 失败 '.json_encode($logData,256));
            }
            // 改变 Order 表里面的 total_price 字段   ； dispatch_price 字段
            $orderUpdateData = [
                'total_price' => Db::raw('original_total_price' . ($newData['total_price_change'] < 0 ? $newData['total_price_change'] : '+'.$newData['total_price_change'])),
                'dispatch_price' => Db::raw('original_dispatch_price' . ($newData['dispatch_price_change'] < 0 ? $newData['dispatch_price_change'] : '+'.$newData['dispatch_price_change'])),
            ];
            $jieguo = Db::name('Order')->where('id',$orderId)->setField($orderUpdateData);
            if (false === $jieguo) {
                exception('更新 Order 失败 '.json_encode($orderUpdateData,256));
            }
            // 提交事务
            Db::commit();

            return $this->retSuccess('改价成功');
        } catch (\Exception $e) {
            // 统一处理错误日志
            Log::error('OrderLogic => changeOrderPrice ' . $e->getMessage());
            // 回滚事务
            Db::rollback();

            return $this->retError('改价失败，请联系管理员');
        }
    }

    /**
     * 变更订单 全部 管理员 和 会员都可以使用本方法
     * @param $orderId
     * @param $adminId
     * @param $postData
     * @return array
     */
    public function changeOrder($orderId, $adminId,$memberId, $postData)
    {
        if (empty($orderId)) {
            return $this->retError('订单序号 无效，请重新登陆');
        }
        if (empty($adminId) && empty($memberId)) {
            return $this->retError('操作人员信息 无效，请重新登陆');
        }
        $model = $this->_getOrderModelById($orderId);
        if (empty($model)) {
            return $this->retError('订单 无效，请重新刷新页面提交');
        }
        // 会员操作的必须检测是否为自己的订单
        if($memberId > 0){
            if($model['member_id'] != $memberId){
                return $this->retError('无法操作别人的订单');
            }
        }

        // 允许修改的列
        $allowFields = [
            'seller_remark',
            'status',
            'status_step', // 步进方式修改状态，推荐 +1 或者 -1
            'address_json',
            'send',
            'cancel_send_remark',
            'delete_time',
            'remark',
        ];
        if (array_key_exists('address', $postData)) {
            // 有更新地址 改成数据库字段
            $postData['address_json'] = $postData['address'];
            unset($postData['address']);
        }
        $oldData = [];
        $newData = [];

        if (!empty($postData['id'])) {
            unset($postData['id']);
        }
        // --------- 获取日志和状态检测 -----------------
        $jieguo = $this->getOrderPayLogData($model, $postData);
        if($jieguo['err_code'] != 0){
            return $jieguo;
        }
        $orderPayLogData = $jieguo['data'];
        unset($postData['order_pay_log']);
        // --------- 获取日志和状态检测 完 -----------------

        foreach ($postData as $key => $item) {
            if (!in_array($key, $allowFields)) {
                return $this->retError($key .' 不允许修改，请重新刷新页面提交');
            }
            switch ($key){
                case 'status_step':// 步进试修改状态
                    $oldData[$key] = $model['status'];
                    $newData[$key] = $postData[$key];
                    break;
                case 'cancel_send_remark':// 处理 取消发货
                    $oldData[$key] = [
                        'express_com' => $model['oe_express_com'],
                        'express' => $model['oe_express'],
                        'express_sn' => $model['oe_express_sn'],
                    ];
                    $newData[$key] = $postData[$key];
                    break;
                case 'send':// 处理 确认发货
                    $oldData[$key] = [
                        'express_com' => $model['oe_express_com'],
                        'express' => $model['oe_express'],
                        'express_sn' => $model['oe_express_sn'],
                    ];
                    $newData[$key] = $postData[$key];
                    break;
                default:// 默认流程
                    $oldData[$key] = $model[$key];
                    $newData[$key] = $postData[$key];
                    break;
            }
        }

        // 启动事务
        Db::startTrans();
        try {
            // 写日志
            $logData = [
                'order_id' => $orderId,
                'admin_id' => $adminId,
                'member_id' => $memberId,
                'old_data' => json_encode($oldData,256),
                'new_data' => json_encode($newData,256),
                'create_time' => time(),
            ];
            $jieguo = Db::name('OrderLog')->insertGetId($logData);
            if ($jieguo < 1) {
                exception('插入 OrderLog 失败 '.json_encode($logData,256));
            }
            // ------------ 写日志 完 ----------------

            /**
             * 处理地址变更
             */
            if (array_key_exists('address_json', $newData)) {
                $this->_changeOrderHandleAddress($orderId,$model['address'],$newData['address_json']);

                // 处理完，剔除
                unset($newData['address_json']);
            }

            /**
             * 处理发货
             */
            if (array_key_exists('send', $newData)) {
                $this->_changeOrderHandleSend($orderId,$model,$newData['send']);

                // 处理完，剔除
                unset($newData['send']);
            }
            /**
             * 处理取消发货
             */
            if (array_key_exists('cancel_send_remark', $newData)) {
                // 处理完，剔除
                unset($newData['cancel_send_remark']);
            }
            // 处理步进 式 订单状态 无联动
            if (array_key_exists('status_step', $newData)) {
                $orderStatus = $model['status'];

                // 增加时，有联动
                if('+1' == $newData['status_step']){
                    $orderStatus = $orderStatus + 1;

                    // 为 2 待发货 时
                    if(2 == $orderStatus){
                        $this->_orderStatusLinkageOrderPayLog($orderPayLogData);
                    }
                }
                if('-1' == $newData['status_step']){
                    $orderStatus = $orderStatus - 1;
                }

                $statusStepData['update_time'] = time();
                $statusStepData['status'] = $orderStatus;
                $jieguo = Db::name('Order')->where('id', $orderId)->setField($statusStepData);

                if (false === $jieguo) {
                    exception('更新 Order 失败 '.json_encode($statusStepData,256));
                }

                // 处理完，剔除
                unset($newData['status_step']);
            }

            if (!empty($newData)) {
                $newData['update_time'] = time();
                $jieguo = Db::name('Order')->where('id', $orderId)->setField($newData);

                if (false === $jieguo) {
                    exception('更新 Order 失败 '.json_encode($newData,256));
                }
            }

            // 如果修改的是状态 根据状态分别进行相关操作
            if (array_key_exists('status', $newData)) {
                // 改成 2
                if(2 == $newData['status']){
                    $this->_orderStatusLinkageOrderPayLog($orderPayLogData);
                }
            }

            // 提交事务
            Db::commit();

            return $this->retSuccess('订单变更成功');
        } catch (\Exception $e) {
            // 统一处理错误日志
            Log::error('OrderLogic => changeOrder ' . $e->getMessage());
            // 回滚事务
            Db::rollback();

            return $this->retError('订单变更失败，请联系管理员');
        }
    }

    /**
     * 后台调用 订单变更 status = 2 时自动使用后台付款的附加信息
     * @param $orderId
     * @param $adminId
     * @param $postData
     * @return array
     */
    public function backChangeOrder($orderId, $adminId, $postData)
    {
        if (array_key_exists('status', $postData)) {
            // 确认付款 需要附加数据
            if(2 == $postData['status']){
                // status = 2 时自动使用后台付款的附加信息
                $postData['order_pay_log'] = [
                    'pay_log_id' => 0,
                    'payment_method' => 2,
                    'money' => 0,
                ];
            }
        }

        if (array_key_exists('type', $postData)) {
            // 处理确认发货的转换
            if('send' == $postData['type']){
                // 确认付款 需要附加数据
                $postData['status'] = 3;
            }
            // 处理 取消发货
            if('cancel_send' == $postData['type']){
                $postData['status_step'] = -1;
            }

            unset($postData['type']);
        }

        return $this->changeOrder($orderId,$adminId,0,$postData);
    }

    /**
     * 确认收货
     * @param $orderId
     * @param $adminId
     * @return array
     */
    public function backOrderConfirmFinish($orderId, $adminId){
        $postData = ['status' => 4];
        return $this->backChangeOrder($orderId,$adminId,$postData);
    }

    /**
     * 确认付款（后台付款），通常情况下为后台操作
     * @param $orderId
     * @param $adminId
     * @return array
     */
    public function backOrderConfirmPay($orderId, $adminId){
        $postData = ['status' => 2];
        return $this->backChangeOrder($orderId,$adminId,$postData);
    }

    /**
     * 后台 关闭订单
     * @param $orderId
     * @param $adminId
     * @return array
     */
    public function backOrderCloseOrder($orderId, $adminId){
        $postData = ['status' => 0];
        return $this->backChangeOrder($orderId,$adminId,$postData);
    }

    /**
     * 订单状态 联动 之 OrderPayLog
     */
    private function _orderStatusLinkageOrderPayLog($orderPayLogData)
    {
        $jieguo = Db::name('OrderPayLog')->insertGetId($orderPayLogData);
        if ($jieguo < 1) {
            exception('插入 OrderPayLog 失败 '.json_encode($orderPayLogData,256));
        }
    }

    /**
     * 步进式 订单状态检测
     * @param $orderStatus
     * @param $postStatus
     * @return array
     */
    private function chackStatusStep($orderStatus, $postStatusStep)
    {
        // 已经关闭的订单不可修改
        if(0 == $orderStatus){
            return $this->retError('已经关闭的订单不可修改');
        }

        if(4 == $orderStatus){
            return $this->retError('已经完成的订单不可修改');
        }

        if('-1' == $postStatusStep){
            // 待付款 和 待收货 的状态可以退回
            if(1 != $orderStatus && 3 != $orderStatus){
                Log::info('当前状态不允许退回操作 $orderStatus：'.$orderStatus .' $postStatusStep：'.$postStatusStep);

                return $this->retError('当前状态不允许退回操作');
            }
        }
//
//        if('+1' == $postStatusStep){
//
//        }

        return $this->retSuccess('通过');
    }

    /**
     * 订单状态检测
     * @param $orderStatus
     * @param string $postStatus
     * @return array
     */
    private function chackStatus($orderStatus, $postStatus)
    {
        // 已经关闭的订单不可修改
        if(0 == $orderStatus){
            return $this->retError('已经关闭的订单不可修改');
        }
        if($postStatus > 4){
            Log::info('提交 状态 不在允许范围 $orderStatus：'.$orderStatus .' $postStatus：'.$postStatus);

            return $this->retError('提交 状态 不在允许范围');
        }
        // 待付款 时可以 关闭订单，其他状态 不允许逆向修改 不允许跨步修改
        if(1 == $orderStatus){
            if($postStatus != 0 && $postStatus != ($orderStatus+1)){
                Log::info('不允许逆向修改 不允许跨步修改 $orderStatus：'.$orderStatus .' $postStatus：'.$postStatus);

                return $this->retError('不允许逆向修改 不允许跨步修改 状态');
            }
        }
        // 3 待收货 时 可取消发货，或者 已完成
        if(3 == $orderStatus){
            if($postStatus != -1 && $postStatus != 4){
                Log::info('不允许逆向修改 不允许跨步修改 $orderStatus：'.$orderStatus .' $postStatus：'.$postStatus);

                return $this->retError('不允许逆向修改 不允许跨步修改 状态');
            }
        }
        else{
            // 不允许跨步修改
            if($postStatus != ($orderStatus+1) && $postStatus != ($orderStatus-1)){
                Log::info('不允许跨步修改 $orderStatus：'.$orderStatus .' $postStatus：'.$postStatus);

                return $this->retError('不允许跨步修改 状态');
            }
        }

        return $this->retSuccess('通过');
    }

    /**
     * 获取订单支付日志
     * @param array $orderModel
     * @param array $postData
     * @return array 组装好后的数据
     */
    private function getOrderPayLogData($orderModel, $postData)
    {
        $orderPayLogMoney = 0.0;
        $orderPayLogPaymentMethod = 0;
        $orderPayLogPayLogId = 0;

        $orderStatus = $orderModel['status'];
        $isChackAdditionalData = false;

        if (array_key_exists('status_step', $postData)) {
            $jieguo = $this->chackStatusStep($orderModel['status'],$postData['status_step']);
            if($jieguo['err_code'] != 0){
                return $jieguo;
            }
            // 增加时，有联动
            if('+1' == $postData['status_step']){
                $orderStatus = $orderStatus + 1;
                // 增加时，需要检测附加数据
                $isChackAdditionalData = true;
            }
            if('-1' == $postData['status_step']){
                $orderStatus = $orderStatus - 1;
            }
        }
        if (array_key_exists('status', $postData)) {
            $jieguo = $this->chackStatus($orderModel['status'],$postData['status']);
            if($jieguo['err_code'] != 0){
                return $jieguo;
            }
            $orderStatus = $postData['status'];
            $isChackAdditionalData = true;
        }
        /**
         * 需要检测附加数据
         */
        if ($isChackAdditionalData) {
            // 确认付款 需要附加数据
            if(2 == $orderStatus){
                if(empty($postData['order_pay_log'])){
                    Log::info('order_pay_log array 未提交 $postData：'.json_encode($postData,256));

                    return $this->retError('需提交 确认付款 附加数据，请重新刷新页面提交');
                }
                $orderPayLogTmp = $postData['order_pay_log'];
                if(empty($orderPayLogTmp['payment_method'])){
                    Log::info('order_pay_log array => payment_method 未提交 $postData：'.json_encode($postData,256));

                    return $this->retError('需提交 付款方式，请重新刷新页面提交');
                }

                $orderPayLogPaymentMethod = $orderPayLogTmp['payment_method'];

                if ($orderPayLogTmp['payment_method'] != 2 && empty($orderPayLogTmp['money'])) {
                    Log::info('order_pay_log array => payment_method = 2 ，money 未提交 $postData：'.json_encode($postData,256));

                    return $this->retError('需提交 付款金额，请重新刷新页面提交');
                }
                elseif(2 == $orderPayLogTmp['payment_method']){
                    // 后台付款 自动输入 订单应付金额
                    $orderPayLogMoney = (getOrderPayableByModel($orderModel) * 100); // 转换成分
                }
                else{
                    // 不为 内部付款（包含余额付款、后台付款等） 需要提交交易流水ID
                    if(empty($orderPayLogTmp['pay_log_id'])){
                        Log::info('order_pay_log array => pay_log_id 未提交 $postData：'.json_encode($postData,256));

                        return $this->retError('流水ID错误，请重新刷新页面提交');
                    }

                    $orderPayLogPayLogId = $orderPayLogTmp['pay_log_id'];
                    $orderPayLogMoney = $orderPayLogTmp['money'];
                }
            }
            // 确认发货 需要的附加数据
            if(3 == $orderStatus){
                if(empty($postData['send'])){
                    Log::info('order_express array 未提交 $postData：'.json_encode($postData,256));

                    return $this->retError('需提交 确认发货 附加数据，请重新刷新页面提交');
                }
            }
        }

        return $this->retSuccess('通过',[
            'order_id' => $orderModel['id'],
            'pay_log_id' => $orderPayLogPayLogId,
            'payment_method' => $orderPayLogPaymentMethod,
            'money' => $orderPayLogMoney,
            'create_time' => time(),
        ]);
    }

    /**
     * 订单变更 处理 之 地址变更
     * @param $orderId
     * @param $addressModel
     * @param $newAddressModel
     * @throws \Exception
     */
    private function _changeOrderHandleAddress($orderId,$addressModel,$newAddressModel)
    {
        $updateAddressData = [];

        if($addressModel['realname'] != $newAddressModel['realname']){
            $updateAddressData['realname'] = $newAddressModel['realname'];
        }
        if($addressModel['mobile'] != $newAddressModel['mobile']){
            $updateAddressData['mobile'] = $newAddressModel['mobile'];
        }

        // 勾选了 修改地址按钮
        if (!empty($newAddressModel['changead'])) {
            if($addressModel['province'] != $newAddressModel['province']){
                $updateAddressData['province'] = $newAddressModel['province'];
            }
            if($addressModel['city'] != $newAddressModel['city']){
                $updateAddressData['city'] = $newAddressModel['city'];
            }
            if($addressModel['area'] != $newAddressModel['area']){
                $updateAddressData['area'] = $newAddressModel['area'];
            }
            if($addressModel['address'] != $newAddressModel['address']){
                $updateAddressData['address'] = $newAddressModel['address'];
            }
        }

        // 有需要修改的
        if(!empty($updateAddressData)){
            // 更新地址
            $jieguo = Db::name('OrderAddress')->where('order_id', $orderId)->setField([
                'address_json' => json_encode(array_merge($addressModel,$updateAddressData),256),
            ]);

            if (false === $jieguo) {
                exception('更新 OrderAddress 失败 '.json_encode($updateAddressData,256));
            }
        }
    }

    /**
     * 订单变更 处理 之 确认发货
     * @param $orderId
     * @param $addressModel
     * @param $newAddressModel
     * @throws \Exception
     */
    private function _changeOrderHandleSend($orderId,$orderModel,$sendData)
    {
        $updateExpressData['update_time'] = time();

        if($orderModel['oe_express'] != $sendData['oe_express']){
            $updateExpressData['express'] = $sendData['oe_express'];
        }
        if($orderModel['oe_express_com'] != $sendData['oe_express_com']){
            $updateExpressData['express_com'] = $sendData['oe_express_com'];
        }
        if($orderModel['oe_express_sn'] != $sendData['oe_express_sn']){
            $updateExpressData['express_sn'] = $sendData['oe_express_sn'];
        }

        // 判断是否存在
        if(Db::name('OrderExpress')->where('order_id',$orderId)->count() > 0){
            // 存在
            // 更新
            $jieguo = Db::name('OrderExpress')->where('order_id', $orderId)->setField($updateExpressData);

            if (false === $jieguo) {
                exception('更新 OrderExpress 失败 '.json_encode($updateExpressData,256));
            }
        }
        else{
            $updateExpressData['order_id'] = $orderId;
            // 插入
            $jieguo = Db::name('OrderExpress')->insertGetId($updateExpressData);

            if ($jieguo < 1) {
                exception('插入 OrderExpress 失败 '.json_encode($updateExpressData,256));
            }
        }
    }

    /**
     * 按 $orderId 获取支付日志
     * @param $orderId
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function _getOrderPayLogListByOrderId($orderId)
    {
        return Db::name('OrderPayLog')->where('order_id', $orderId)->select();
    }

    /**
     * 会员删除订单 ，软删除
     * @param $memberId
     * @param $orderId
     * @return array
     */
    public function memberDelOrder($memberId,$orderId){
        $postData['delete_time'] = time();
        return $this->changeOrder($orderId,0,$memberId,$postData);
    }

    /**
     * 会员取消订单  后退一步
     * @param $memberId
     * @param $orderId
     * @return array
     */
    public function memberCancelOrder($memberId,$orderId){
        $postData['status_step'] = -1;
        return $this->changeOrder($orderId,0,$memberId,$postData);
    }
}